package com.wholesale;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.PaymentMethod;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;
import com.wholesale.utils.PaymentMethodListAdapter;

public class OrderPaymentMethodLayout extends LinearLayout implements
		OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private ListView bodyList;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private RelativeLayout loadingLayout;

	private PaymentMethod currentPaymentMethod;
	private PaymentMethodListAdapter listAdapter;
	private CategoriesListAsync categoriesAsync;
	public static double userBalance = 0.00d;
	private double totalPrice;

	// 构造函数
	public OrderPaymentMethodLayout(Context context,
			final ViewFlipper viewFlipper, double totalPrice, int selectIndex,
			PaymentMethod currentPaymentMethod) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		this.currentPaymentMethod = currentPaymentMethod;
		this.totalPrice = totalPrice;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.ordershipmethod, this);
		bodyList = (ListView) baseView.findViewById(R.id.bodyList);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Back");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setVisibility(View.GONE);
		rightButton.setText("OK");
		rightButton.setOnClickListener(this);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("Payment Method");
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);

		bodyList.setSelector(R.drawable.categories_list_bg);
		// item 单击事件
		bodyList.setOnItemClickListener(moreClieckListener);
		listAdapter = new PaymentMethodListAdapter(context, bodyList);
		listAdapter.setSelected(selectIndex);
		bodyList.setAdapter(listAdapter);

		categoriesAsync = new CategoriesListAsync(context);
		categoriesAsync.execute((Void) null);
	}

	public void dialog(String title, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Cancle",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	// ListView 点击事件
	OnItemClickListener moreClieckListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			PaymentMethod temp = listAdapter.getItem(arg2);
			if (temp.getPayName().equalsIgnoreCase("Use balances")) {
				double total = totalPrice + temp.getPayFee();
				if (total > userBalance) {
					dialog("Sorry",
							"Your balance is not enough to pay this order.");
					// currentPaymentMethod = listAdapter.getItem(arg2);
					// 如果不足，不允许选择
					return;
				} else {
					currentPaymentMethod = listAdapter.getItem(arg2);
					// listAdapter.setSelected(arg2);
					// listAdapter.notifyDataSetChanged();
					// bodyList.postInvalidate();
				}
			} else {
				currentPaymentMethod = listAdapter.getItem(arg2);
				// listAdapter.setSelected(arg2);
				// listAdapter.notifyDataSetChanged();
				// bodyList.postInvalidate();
			}
			int count = viewFlipper.getChildCount();
			View preView = viewFlipper.getChildAt(count - 2);
			if (preView.getClass().getName()
					.equals(CheckOutLayout.class.getName())) {
				((CheckOutLayout) preView).setPaymentMethod(arg2,
						currentPaymentMethod);
			}
			viewFlipper.showPrevious();
			viewFlipper.removeView(OrderPaymentMethodLayout.this);
		}
	};

	class CategoriesListAsync extends
			AsyncTask<Void, Integer, ArrayList<PaymentMethod>> {
		ProgressDialog pdialog;

		public CategoriesListAsync(Context context) {
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<PaymentMethod> doInBackground(Void... params) {
			userBalance = WebServiceClient.getUserBalance(
					Constants.loginResponse.getUserId(),
					Constants.loginResponse.getUserToken());
			listAdapter.setBalance(userBalance);
			return WebServiceClient.getPaymentMethods();
		}

		@Override
		protected void onPostExecute(ArrayList<PaymentMethod> result) {
			listAdapter.clear();
			listAdapter.addItems(result);
			if (currentPaymentMethod != null) {
				int size = result.size();
				int curIndex = 0;
				for (int i = 0; i < size; i++) {
					if (result.get(i).getPayId() == currentPaymentMethod
							.getPayId()) {
						curIndex = i;
						break;
					}
				}
				listAdapter.setSelected(curIndex);
			} else if (result.size() > 0) {
				currentPaymentMethod = result.get(0);
			}
			listAdapter.notifyDataSetChanged();
			// pdialog.dismiss();
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftBtn:
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			if (currentPaymentMethod != null) {
				// int count = viewFlipper.getChildCount() ;
				// View preView = viewFlipper.getChildAt(count-2);
				// if(preView.getClass().getName().equals(CheckOutLayout.class.getName())){
				// ((CheckOutLayout)preView).setPaymentMethod(currentPaymentMethod);
				// }
				// viewFlipper.showPrevious();
				// viewFlipper.removeView(this);
			}
			break;
		default:
			break;
		}

	}
}
